package com.jf.blogbackened.service.impl;

import com.jf.blogbackened.bean.Article;
import com.jf.blogbackened.bean.PageBean;
import com.jf.blogbackened.bean.Result;
import com.jf.blogbackened.bean.vo.ArticleVO;
import com.jf.blogbackened.mapper.ArticleMapper;
import com.jf.blogbackened.service.ArticleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author David
 */
@Service
public class ArticleServiceImpl implements ArticleService {
    @Resource
    private ArticleMapper articleMapper;

    @Override
    public Result getAllArticles(Article article, Integer currentPage, Integer pageSize) {
        // 分页逻辑
        // 当前页码，总记录数，总页数，每页显示的记录数
        // 1 获取满足条件的总记录数
        int total = articleMapper.getCount(article);
        // 2 计算总页数
        int totalPage = total%pageSize == 0 ?total / pageSize:(total / pageSize)+1;
        // 3计算偏移量offset
        Integer offset =(currentPage-1)*pageSize;
        // 4 查询数据
        List<ArticleVO> articleVOList= articleMapper.getPageData(article,offset,pageSize);
        // 5 创建分页对象
        PageBean<ArticleVO> pageBean = new PageBean<>(articleVOList,total,pageSize);
        pageBean.setCurrentPage(currentPage);
        pageBean.setPageCount(totalPage);
        // 6 返回
        return Result.ok().data(pageBean);
    }

    @Override
    public Result addOrUpdateArticle(Article article) {
        int i=0;
        if (article.getId()==null) {
            article.setCover("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png");
            // 将文章发布时间设定为当前系统时间
            article.setCreated(System.currentTimeMillis());
            article.setModified(System.currentTimeMillis());
            article.setHits(0);
            article.setTransfer(0);
           i = articleMapper.insert(article);
        }else {
            // 有id走update更新
            article.setModified(System.currentTimeMillis());
            i = articleMapper.update(article);
        }
        if (i > 0) {
            return Result.ok();
        }else {
            return Result.error("服务器出现未知异常");
        }
    }

    @Override
    public Result getArticlesById(Integer id) {
        Article article=articleMapper.getArticlesById(id);
        if (article!= null) {
            return Result.ok().data(article);
        }else {
            return Result.error("参数非法");
        }
    }

    @Override
    public Result delArticleById(Integer id) {
       Integer i=articleMapper.delArticleById(id);
        if (i!= 0) {
            return Result.ok().data(i);
        }else {
            return Result.error("服务器内部异常");
        }
    }
}
